package com.seek.service.imp;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.seek.core.BaseServiceImpl;
import com.seek.dao.SysmsgDao;
import com.seek.model.entity.TSysmsg;
import com.seek.service.SysmsgService;
import com.seek.util.BeanUtils;
import com.seek.util.CommonUtil;
import com.seek.util.DateUtil;

/**
 * @author lushuangteng
 *
 */
@Repository("sysmsgService")
public class SysmsgServiceImpl extends BaseServiceImpl<TSysmsg> implements SysmsgService {
	@Autowired
	public void setDao(SysmsgDao sysmsgDao) {
		super.setDao(sysmsgDao);
	}
	public SysmsgDao getDao() {
		return (SysmsgDao) super.getDao();
	}
	
	@Transactional
	public TSysmsg save(JSONObject reqJson) throws Exception{
		TSysmsg en = new TSysmsg();
		if (CommonUtil.getLongValue((reqJson.getString("msgId")))>0){
			en.setId(CommonUtil.getLongValue(reqJson.getString("msgId")));
		}
		en.setCompanyId(reqJson.getLong("companyId"));
		en.setTitle(reqJson.getString("title"));
		en.setContent(reqJson.getString("content"));
		en.setNeedSendTime(DateUtil.dateFormat(reqJson.getString("needSendTime"), DateUtil.DATE_FORMAT_YMDHMS));
		
		if (CommonUtil.isEmpty(en.getTitle()) || CommonUtil.isEmpty(en.getContent()) || en.getNeedSendTime()==null){
			throw new Exception("缺少必须的参数，请检查");
		}
		
		if (en.getId() == null || en.getId() < 1){
			en.setType(1);
			en.setReciveId(-1L);
			en.setStatus(0);
			
			en.setIsUsed(1);
			en.setCreateTime(new Date());
			en.setCreateUserId(CommonUtil.getLongValue(reqJson.getString("_currnetUserId")));
			en.setModifyTime(new Date());
			en.setModifyUserId(en.getCreateUserId());
			en = this.getDao().insert(en);
		}else{
			en.setModifyTime(new Date());
			en.setModifyUserId(CommonUtil.getLongValue(reqJson.getString("_currnetUserId")));
			TSysmsg old = this.getDao().get(en.getId());
			BeanUtils.copyPropertiesExclude(en, old, new String[]{"id","companyId","type","reciveId","status","params","realSendTime","createUserId","createTime","isUsed"});
			en = this.getDao().update(old);	
		}

		return en;
	}
	
	public void updateMsgSendStatus(String id) throws Exception{
		if (CommonUtil.getIntValue(id) < 1)
			return;
		String sql = "update t_sysmsg set status=3,real_send_time=now() where type=1 and id=?";
		this.getDao().executeUpdateSql(sql, new Object[]{id});
	}
}